package com.example.chirdrenserver.Service.Impl;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.chirdrenserver.Constant.RedisConstant;
import com.example.chirdrenserver.Service.EmailService;
import com.example.chirdrenserver.Utils.RedisCacheUtil;
import com.example.chirdrenserver.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private SimpleMailMessage simpleMailMessage;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Value("${spring.mail.username}")
    String fromName;
    @Override
    public void send(String email, String context) {
        simpleMailMessage.setSubject("儿童抑郁症宣传平台");
        simpleMailMessage.setFrom(fromName);
        simpleMailMessage.setTo(email);
        simpleMailMessage.setText(context);
        javaMailSender.send(simpleMailMessage);
    }

    @Override public boolean checkCode(String email, Integer code) {
        if (ObjectUtils.isEmpty(email) || ObjectUtils.isEmpty(code)) {
            throw new BaseException("参数为空");
        }
        final Object o = redisCacheUtil.get(RedisConstant.EMAIL_CODE + email);

        if (!code.toString().equals(o)) {
            throw new BaseException("验证码不正确");

        }
        return true;
    }
}
